package com.tiles.controller;

import com.tiles.tools.DesUtil;
import com.tiles.tools.Md5Util;
import com.tiles.service.TilesUserService;
import com.tiles.tools.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class UserLoginController {

        @Autowired
        private TilesUserService service;

        @GetMapping("/login")
         public String tilesUserLoginForm(HttpServletRequest request){

            return "login";
        }
        @PostMapping("/login")
        public String tilesUserLogin(@RequestParam String   username, @RequestParam String password, Model model,
                                     HttpServletRequest request, HttpServletResponse response) throws Exception {

            if (username != null && password != null) {
                String key = "tiles";
                //DES用户名加密
                String name = DesUtil.encryption(username, key);
                //Md5 密码加密
                String pwd = Md5Util.md5Password(password);
                int nameAndPwd = service.selectUserByNameAndPassword(name, pwd);
                if (nameAndPwd == 1) {
                    model.addAttribute("msg", "登陆成功");
                    //连接redis
                    Jedis jedis = new Jedis("127.0.0.1", 6379);
                    //获取当前时间
                    String time=System.currentTimeMillis()+"";
                    //用des加密给当前时间加密
                    String token = DesUtil.encryption(time, key);
                    //将token和name 存入redis数据库中
                    jedis.setex(token,3600, name);
                    //关闭redis连接
                    jedis.close();
                    //写入Cookie中
                    CookieUtil.setCookie(response, "token", name, 3600);
                    CookieUtil.setCookie(response, "lastLoginTime", token, 3600);
                    return "redirect:/home";
                } else {
                    model.addAttribute("msg", "用户名密码不正确");
                    return "login";
                }

            } else {
                model.addAttribute("msg", "用户名密码不能为空");
                return "login";
            }
        }
        @GetMapping("/outlogin")
        public String outLogin(HttpServletRequest request,HttpServletResponse response){
            //推出登陆，删除cookie中的登陆信息
            CookieUtil.setCookie(response, "token", null, 0);
            CookieUtil.setCookie(response, "lastLoginTime", null, 0);
            return "redirect:/home";
        }
}
